<template>
  <div class="user_container">

    <el-dialog title="修改用户信息" :visible.sync="showUserUpdate" width="50%" center>
      <el-form :model="userUpdate" label-width="100px" label-position="LabelPosition" ref="userUpdate"
        :rules="userUpdateRules" style="width: 100%;">
        <el-form-item label="工号:" prop="InputUserId" style="width: 60%;">
          <el-input v-model="userUpdate.InputUserId" placeholder="请输入工号" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="姓名:" prop="InputUserName" style="width: 60%;">
          <el-input v-model="userUpdate.InputUserName" placeholder="请输入姓名" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="职位:" prop="InputUserPosition" style="width: 60%;">
          <el-input v-model="userUpdate.InputUserPosition" placeholder="请输入职位" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属部门:" prop="SelectUserDepartment" style="width: 60%;">
          <el-select v-model="userUpdate.SelectUserDepartment" placeholder="请选择所属部门" clearable>
            <el-option label="销售部" value="销售部"></el-option>
            <el-option label="财务部" value="财务部"></el-option>
            <el-option label="市场部" value="市场部"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色:" prop="CheckboxRole" style="width: 80%;">
          <el-checkbox-group v-model="userUpdate.CheckboxRole">
            <el-checkbox :label="role.roleName" v-for="role in roleList" :key="role.roleName"></el-checkbox>
            <!-- <el-checkbox label="驾驶员"></el-checkbox>
            <el-checkbox label="部门管理员"></el-checkbox>
            <el-checkbox label="综合办"></el-checkbox> -->
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showUserUpdate = false">取 消</el-button>
        <el-button style="margin-left: 30px;" type="primary" @click="doUpdate('userUpdate')">确定修改</el-button>
      </span>
    </el-dialog>

    <div class="user_header_container">
      <!-- <div class="user_title">用户管理</div> -->
      <el-form ref="form" :model="form" label-width="70px" class="user_header" style="margin-bottom: 0px;">
        <el-form-item label="部门：" class="user_content_select">
          <el-select v-model="form.department" clearable placeholder="请选择部门" class="user_content_select_item">
            <el-option v-for="(item, $index) in this.departmentlist" :key="$index" :label="item"
              :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务：" class="user_content_select">
          <el-select v-model="form.position" clearable placeholder="请选择职务" class="user_content_select_item">
            <el-option v-for="(item, $index) in this.positionlist" :key="$index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名：" class="user_content_input">
          <el-input v-model="form.userName" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-button type="primary" class="user_content_button">查询</el-button>
        <el-button type="primary" style="margin-left: 0;" class="user_content_button" @click="ToAddUser()">新建</el-button>
      </el-form>
    </div>
    <!-- <el-divider></el-divider> -->
    <div class="user_table_container">

      <div class="auto-archive-horizon"></div>

      <el-table :data="this.filtedTableData" style="width:100%" :defaultSort="{ prop: 'userId', order: 'descending' }">
        <el-table-column prop="userId" label="工号" min-width="10%" sortable align="center">
        </el-table-column>
        <el-table-column prop="userName" label="姓名" min-width="10%" align="center">
        </el-table-column>
        <el-table-column prop="userPhone" label="电话号码" min-width="15%" align="center">
        </el-table-column>
        <el-table-column prop="userIdNumber" label="身份证" min-width="23%" align="center">
        </el-table-column>
        <el-table-column prop="userAge" label="年龄" min-width="10%" align="center">
        </el-table-column>
        <el-table-column prop="userDepartment" label="所属部门" min-width="10%" align="center">
        </el-table-column>
        <el-table-column prop="userPosition" label="职务" min-width="10%" align="center">
        </el-table-column>
        <el-table-column prop="profit" label="操作" min-width="12%" align="center">
          <template slot-scope="scope">
            <el-button @click="checkDetail(scope.row)" type="text" size="small">查看</el-button>
            <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
            <el-button style="color: red;" @click="deleteThisUser(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="tablePage.pageNum"
        :page-size="tablePage.pageSize" :page-sizes="pageSizes" :total="tablePage.total" @size-change="handleSizeChange"
        @current-change="handlePageChange" style="padding-right: 30px;" />
    </div>
  </div>
</template>
  
<style scoped>
.user_container {
  margin: 0 auto;
  margin-top: 1%;
  width: 95%;
  /* height: 100%; */
  justify-content: center;
  background-color: rgb(255, 255, 255);
}

.user_header_container {
  display: flex;
}

.user_header {
  display: flex;
  align-items: center;
  justify-content: right;
  margin: 20px auto;
  width: 90%;
}

.user_title {
  font-size: xx-large;
  width: 20%;
}

.user_content_select {
  margin: 0 auto;
  width: 28%;
}

.user_content_select_item {
  width: 99%;
}

.user_content_input {
  margin: 0;
  width: 28%;
}

.user_content_button {
  margin: 0 20px;
}

.el-divider--horizontal {
  margin: 5px auto;
  height: 0.5px;
}

.user_table_container {
  width: 90%;
  margin: 0 auto;
}

.auto-archive-horizon {
  margin: 20px 0 0 0;
  height: 1.5px;
  background-color: #ebeef5;
}

.pagination {
  width: 100%;
  margin: 25px auto;
  /* text-align: right; */
}
</style>
  
<script>
import { getAllUser, getAllPosition, getAllDepartment, deleteUser, getUserRole, adminUpdateUser, deleteUserRole, addUserRole, getAllRoles } from '../../api/user';
export default {
  name: 'userView',
  data() {
    return {
      form: {
        department: null,
        position: null,
        userName: null,
      },
      tableData: [],
      departmentlist: [],
      positionlist: [],
      //分页相关数据
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 8, // 每页多少条
        total: 0 // 总记录数
      },
      BasicDataPage: null,
      pageSizes: [4, 8],
      showUserUpdate: false,
      userUpdate: {
        InputUserId: null,
        InputUserName: null,
        InputUserPosition: null,
        SelectUserDepartment: null,
        CheckboxRole: [],
      },
      userUpdateRules: {
        InputUserId: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 8, max: 8, message: '长度为8个字符', trigger: 'blur' }
        ],
        InputUserName: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
        InputUserPosition: [{ required: true, message: '请选择职位', trigger: 'blur' },],
        SelectUserDepartment: [{ required: true, message: '请选择所属部门', trigger: 'change' },],
        CheckboxRole: [{ required: true, message: '请选择至少一位角色', trigger: 'change' },],
      },
      userUpdateCommit: {
        userId: null,
        userPosition: null,
        userDepartment: null
      },
      userRoleAdd: [],
      SubmitCode: [],
      roleList: [],
    }
  },
  computed: {
    filtedTableData() {
      if (!this.form.department && !this.form.position && !this.form.userName) {
        return this.getPageList(this.tableData, this.tablePage.pageNum, this.tablePage.pageSize)
      } else {
        return this.getPageList(this.tableData.filter((value) => {
          const departmentMatch = !this.form.department || value.userDepartment.includes(this.form.department);
          const positionMatch = !this.form.position || value.userPosition.includes(this.form.position);
          const userNameMatch = !this.form.userName || value.userName.includes(this.form.userName);
          return departmentMatch && positionMatch && userNameMatch;
        }), this.tablePage.pageNum, this.tablePage.pageSize)
      }
    }
  },
  methods: {
    // 分页
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage
      // 在此刷新数据
      this.BasicDataPage = this.getList(this.tableData, this.tablePage.pageNum, this.tablePage.pageSize)
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      // 在此刷新数据
      this.BasicDataPage = this.getList(this.tableData, this.tablePage.pageNum, this.tablePage.pageSize)
    },
    getList(data, num, size) {
      let list, start, end
      start = (num - 1) * size
      end = start + size
      list = data.filter((item, index) => {
        return index >= start && index < end
      })
      list.forEach((item, index) => {
        item.seq = index + start
      })
      return list
    },
    getPageList(data, num, size) {
      this.tablePage.total = data.length
      this.BasicDataPage = this.getList(data, num, size)
      return this.BasicDataPage
    },
    initTableData() {
      getAllUser().then(res => {
        this.tableData = res.data.data;
      })
    },
    intDepartmentSelect() {
      getAllDepartment().then(res => {
        this.departmentlist = res.data.data;
      })
    },
    intPositionSelect() {
      getAllPosition().then(res => {
        this.positionlist = res.data.data;
      })
    },
    checkDetail(row) {
      this.$router.push({
        path: "/Home/UserDetail",
        query: {
          Name: row.userName,
          Id: row.userId,
          Phone: row.userPhone,
          IdNumber: row.userIdNumber,
          Age: row.userAge,
          Department: row.userDepartment,
          Position: row.userPosition,
        }
      });
    },
    ToAddUser() {
      this.$router.push("/Home/AddUser")
    },
    deleteThisUser(row) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.userId).then(res => {
          if (res.data.code == '0') {
            this.$message({
              message: res.data.msg,
              duration: 2000,
              showClose: true,
              type: 'success'
            });
            setTimeout(() => {
              location.reload();
            }, 700)
          }
          else {
            this.$message.error(res.data.msg);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    showUpdateDialog(row) {
      this.showUserUpdate = true;
      this.userUpdate.InputUserId = row.userId;
      this.userUpdate.InputUserName = row.userName;
      this.userUpdate.InputUserPosition = row.userPosition;
      this.userUpdate.SelectUserDepartment = row.userDepartment;

      getUserRole(row.userId).then(res => {
        this.userUpdate.CheckboxRole.length = 0;
        for (var i = 0; i < res.data.data.length; i++) {
          this.userUpdate.CheckboxRole.push(res.data.data[i].userRole)
        }
      })
    },

    doUpdateUser() {
      return new Promise((resolve, reject) => {

        this.userUpdateCommit.userId = this.userUpdate.InputUserId
        this.userUpdateCommit.userPosition = this.userUpdate.InputUserPosition
        this.userUpdateCommit.userDepartment = this.userUpdate.SelectUserDepartment
        adminUpdateUser(this.userUpdateCommit).then(res => {
          this.SubmitCode.push(res.data.code);
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
      });
    },

    doDeleteUserRole() {
      return new Promise((resolve, reject) => {

        deleteUserRole(this.userUpdateCommit.userId).then(res => {
          this.SubmitCode.push(res.data.code);
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
      });
    },
    doAddUserRole() {
      return new Promise((resolve, reject) => {

        for (let i = 0; i < this.userUpdate.CheckboxRole.length; i++) {
          let newItem = {
            userId: this.userUpdate.InputUserId,
            userRole: this.userUpdate.CheckboxRole[i]
          };
          this.userRoleAdd.push(newItem)
        }

        addUserRole(this.userRoleAdd).then(res => {
          this.SubmitCode.push(res.data.code);
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
      });
    },
    doUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将修改该用户的信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.doUpdateUser()
              .then(() => this.doDeleteUserRole())
              .then(() => this.doAddUserRole())
              .then(() => {
                this.JudgeSuccess(this.SubmitCode);
              })
              .catch(error => {
                console.log(error);
                this.$message.error('提交失败: ' + error);
              });

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
        else {
          return false;
        }
      })
    },
    JudgeSuccess(data) {
      if (this.JudgeSubmitCode(data)) {
        this.showMessage('修改成功', 'success');
        this.showUserUpdate = false
        setTimeout(() => {
          location.reload()
        }, 700)
      } else
        this.showMessage('修改失败', 'error');
    },
    JudgeSubmitCode(data) {
      const allZeros = data.every(code => code === '0');
      return allZeros;
    },
    showMessage(message, type) {
      this.$message({
        message: message,
        duration: 2000,
        showClose: true,
        type: type,
      });
    },
  },

  mounted() {
    this.initTableData();
    this.intDepartmentSelect();
    this.intPositionSelect();
    getAllRoles().then(res => {
      this.roleList = res.data.data
    })
  }
}
</script>
  